#!/bin/bash
# launcher — เปิดปุ๊บใช้ปั๊บ: library ยัดมาในแอปแล้ว ไม่ต้องติดตั้ง ไม่ต้องมีเน็ต
# ถ้า Python ของเครื่องไม่เข้ากับ lib ที่ยัดมา → fallback ไปติดตั้งเองอัตโนมัติ

RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
SUPPORT="$HOME/Library/Application Support/LiveStudioSolver"
mkdir -p "$SUPPORT"
cd "$SUPPORT" || exit 1

PY=""
for c in /usr/bin/python3 python3 /opt/homebrew/bin/python3 /usr/local/bin/python3; do
  if [ -x "$c" ] || command -v "$c" >/dev/null 2>&1; then
    if "$c" -c 'import sys;exit(0 if sys.version_info>=(3,9) else 1)' 2>/dev/null; then
      PY="$c"; break
    fi
  fi
done
if [ -z "$PY" ]; then
  osascript -e 'display dialog "ไม่พบ Python — เปิด Terminal แล้วพิมพ์:  xcode-select --install  แล้วลองเปิดโปรแกรมใหม่" buttons {"OK"} default button "OK" with title "Live Studio Solver" with icon caution'
  exit 1
fi

# ทางที่ 1: ใช้ library ที่ยัดมาในแอป
# หมายเหตุ: ไม่เอา PIL มาเป็นเงื่อนไขเปิดโปรแกรม เพราะถ้า PIL ของเครื่อง
# ไม่เข้ากัน จะทำให้ทุกคนตกไปทางที่ 2 (ช้า 30 วิ) ทั้งที่ตัวโปรแกรมใช้ได้ปกติ
# — PIL ขาดแค่ทำให้ "วัดช่องว่างเอง" ไม่ทำงาน ส่วนที่เหลือยังครบ
if PYTHONPATH="$RES/lib" "$PY" -c "import websocket, requests, pydantic, webview" >/dev/null 2>&1; then
  export PYTHONPATH="$RES/lib"
  exec "$PY" "$RES/app_ui.py"
fi

# ทางที่ 2 (fallback): Python เครื่องนี้ไม่เข้ากับ lib ที่ยัดมา → ติดตั้งเอง
VENV="$SUPPORT/.venv"
DEPS="requests pydantic pywebview websocket-client Pillow"
if ! "$VENV/bin/python" -c "import websocket, requests, pydantic, webview" >/dev/null 2>&1; then
  osascript -e 'display notification "ติดตั้งครั้งแรก ~30 วิ รอสักครู่..." with title "Live Studio Solver"'
  [ -x "$VENV/bin/python" ] || "$PY" -m venv "$VENV"
  "$VENV/bin/python" -m pip install -q --upgrade pip
  if ! "$VENV/bin/python" -m pip install -q $DEPS; then
    rm -rf "$VENV"
    osascript -e 'display dialog "ติดตั้งไม่สำเร็จ — ตรวจอินเทอร์เน็ตแล้วเปิดใหม่" buttons {"OK"} default button "OK" with title "Live Studio Solver" with icon stop'
    exit 1
  fi
fi
exec "$VENV/bin/python" "$RES/app_ui.py"
